<?php

class AuthController extends Zend_Controller_Action
{

    public function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            if ($this->getRequest()->getActionName() == 'login') {
                $this->_redirect('/');
            }
        } else {
            if ($this->getRequest()->getActionName() == 'logout') {
                $this->_redirect('/');
            }
        }
    }

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function loginAction()
    {
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            $form = new Application_Form_Login();
            if ($form->isValid($formData)) {
                $name = $form->getValue('name');
                $password = $form->getValue('password');
                $authAdapter = new Zend_Auth_Adapter_DbTable(null,
                                                             'user',
                                                             'name',
                                                             'password',
                                                             "SHA1(?)");
                $authAdapter->setIdentity($name);
                $authAdapter->setCredential($password);
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) {
                    $this->_redirect('/');
                }
            }
        }
    }

    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_redirect('/');
    }


}





